package com.tea.admin.modules.app.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

public class MapUtil {
    private static final String AmapKey = "2b815e0fa2c506f6a523668728a264b1";
    private static final String AMAP_REMOTE_URL = "https://restapi.amap.com/v3/geocode/geo";

    public static Map<String,String> getGeocode(String address){
        Map<String, Object> localeParamMap =new HashMap<>();
        localeParamMap.put("key", AmapKey);
        localeParamMap.put("address", address);

        // 发送请求获取响应
        String localeResultStr = HttpUtil.get(AMAP_REMOTE_URL, localeParamMap);

        // 解析JSON响应
        JSONObject json = JSONUtil.parseObj(localeResultStr);

        // 检查状态是否为成功
        String status = json.getStr("status");
        if (!"1".equals(status)) {
            throw new RuntimeException("获取经纬度失败: " + status);
        }

        // 获取geocodes数组
        JSONArray geocodes = json.getJSONArray("geocodes");

        if (geocodes != null && !geocodes.isEmpty()) {
            // 假设我们只处理第一个结果
            JSONObject firstResult = geocodes.getJSONObject(0);
            String location = firstResult.getStr("location");

            // 将location字符串拆分为经度和纬度
            if (location != null && !location.isEmpty()) {
                String[] coords = location.split(",");
                if (coords.length == 2) {
                    Map<String, String> result = new HashMap<>();
                    result.put("longitude", coords[0]);
                    result.put("latitude", coords[1]);
                    return result;
                } else {
                    throw new RuntimeException("Unexpected location format: " + location);
                }
            }
        }

        // 如果没有找到匹配的地理编码
        throw new RuntimeException("No geocode found for address: " + address);
    }
}
